// pages/user/person/person.js
const app = getApp();
Page({
  //查看用户信息
  userInfo() {
    //判断用户信息是否存在
    if (this.data.userInfo) {
      wx.redirectTo({
        url: "../personInfo/personInfo",
      });
    }
  },
  //申请接单
  personApply() {
    //判断用户是否登录
    const openid = app.globalData.userInfo.openid;
    const phone = app.globalData.userInfo.phone;
    if (!openid) {
      wx.showToast({ title: "请授权登录", icon: "error" });
      return;
    }
    if (!phone) {
      wx.showToast({
        title: "请先绑定手机号",
        icon: "error",
        success() {
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/user/personInfo/personInfo",
            });
          }, 500);
        },
      });
      return;
    }

    //读取用户接单数据
    wx.request({
      url: `${app.globalData.server}/wxGetUser`,
      data: { openid },
      success: (res) => {
        //console.log(res)
        const { personInfo } = res.data.result;
        if (personInfo) {
          switch (personInfo.status) {
            case "未审核":
              wx.showToast({ title: "正在审核", icon: "error" });
              break;
            case "通过审核":
              wx.showToast({ title: "您已是接单员", icon: "error" });
              break;
            case "未通过审核":
              wx.showModal({
                title: "提示",
                content: "未通过审核，请联系管理员！",
                showCancel: false,
              });
              break;
          }
        } else {
          //用户申请接单员信息不存在
          wx.navigateTo({ url: "../personApply/personApply" });
        }
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },
  //审核接单申请
  personVerify() {
    wx.navigateTo({ url: "../personVerify/personVerify" });
  },
  //关于我们
  personAbout() {
    wx.navigateTo({ url: "../personAbout/personAbout" });
  },
  //复制管理员微信
  copyWX() {
    wx.setClipboardData({ data: "13251639603" });
  },
  getOpenID() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            wx.request({
              url: app.globalData.server + "/wxlogin",
              data: { code: res.code },
              success: (result) => {
                // console.log(result.data.openid);
                //result.data.openid;
                if (result.data.status == "ok") {
                  resolve(result.data.openid);
                } else {
                  console.log(result.data.errMsg);
                  reject("err");
                }
              },
              fail: (error) => {
                console.log(error);
                reject("err");
              },
            });
          } else {
            reject("err");
          }
        },
        fail: (err) => {
          reject("err");
        },
      });
    });
  },
  //读取用户信息
  getUserFromDB(userInfo) {
    //console.log(userInfo)
    return new Promise((resolve, reject) => {
      //向服务端发送数据
      wx.request({
        url: `${app.globalData.server}/wxGetUserInfo`,
        method: "POST",
        data: { userInfo },
        success: (res) => {
          //console.log(res)
          if (res.data.status == "ok") {
            resolve(res.data.value);
          } else {
            reject("err");
          }
        },
        fail: (err) => {
          console.log(err);
          reject("err");
        },
      });
    });
  },
  //授权登录
  userLogin() {
    //显示 加载提示窗口
    wx.showLoading();
    //调用授权登录api
    wx.getUserProfile({
      desc: "获取用户信息，用户登录",
      success: async (res) => {
        // console.log(res);
        //关闭 加载提示窗口
        wx.hideLoading();
        let userInfo = {
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl,
          gender: res.userInfo.gender,
        };
        //获取openid
        const openid = await this.getOpenID();
        //console.log(openid)
        if (openid == "err") {
          wx.showToast({ title: "授权登录失败", icon: "error" });
          return;
        }
        //将openid放入userInfo对象
        userInfo = Object.assign({}, userInfo, { openid });
        //后端判断用户是否存在于数据库中，并返回用户信息
        const rs = await this.getUserFromDB(userInfo);
        //console.log(rs)
        if (rs == "err") {
          wx.showToast({ title: "授权登录失败", icon: "error" });
          return; //直接退出userLogin，不继续向下执行
        } else {
          userInfo = rs;
        }
        //存入data
        this.setData({ userInfo });
        //存入缓存
        wx.setStorageSync("userInfo", userInfo);
        //存入全局变量
        app.globalData.userInfo = userInfo;
        // 管理员鉴权
        this.Admin();
      },
      fail: (err) => {
        //关闭 加载提示窗口
        wx.hideLoading();
        console.log(err);
      },
    });
  },
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    role: "", //用户角色
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //读取全局变量userInfo
    const { userInfo } = app.globalData;
    this.setData({ userInfo });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  Admin() {
    //读取全局变量userInfo
    const { userInfo } = app.globalData;
    //判断当前用户是否为超级管理员
    const oid = userInfo ? userInfo.openid : "";
    if (oid) {
      //判断是否为管理员
      wx.request({
        url: `${app.globalData.server}/wxGetPower/${oid}`,
        success: (res) => {
          const { role } = res.data;
          this.setData({ role });
        },
        fail(err) {
          console.log(err);
        },
      });
    }
  },
  onShow() {
    this.Admin();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
